package com.lyr.udpdemo;

import java.io.*;
import java.net.*;
import java.util.Scanner;

public class ServerThread extends Thread{

    //服务器的serverSocket
    //注意：服务器serverSocket监听的端口号要和客户端的端口号一致，否则无法建立连接
    private DatagramSocket ssocket;

    public ServerThread() {

        super("客服：");
    }

    @Override
    public void run() {
        try {
            // 初始化服务器的serverSocket
            ssocket=new DatagramSocket(9999);
            byte[] bt=new byte[1024];
            DatagramPacket sdp=new DatagramPacket(bt,bt.length);


            while (true){
                ///////////////////////////////// 接收客户端的消息//////////////////

                ssocket.receive(sdp);
                int len=sdp.getLength();
                String cSendSmg=new String(bt,0,len);
                System.out.println(cSendSmg);

             ///////////////////////////////// 发送消息到客户端//////////////////
                // 输出内容到网络，发送到服务器端
                Scanner sc=new Scanner(System.in);
                String strClientMsg=Thread.currentThread().getName();
                strClientMsg+=sc.next();
                // 将需要发送的消息打包到数据包中
                DatagramPacket cdp=new DatagramPacket(strClientMsg.getBytes(),0,
                        strClientMsg.getBytes().length,sdp.getSocketAddress());
                ssocket.send(cdp);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
